package com.edu.demo.controller;

import cn.hutool.core.util.ArrayUtil;
import com.edu.demo.constant.CacheConstants;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.utils.Base64;
import com.edu.demo.utils.FileUtils;
import com.edu.demo.utils.ServletUtils;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: CommonController
 * @Description:
 * @Author: jxw
 * @Date: 2023-01-14
 */
@RestController
//@CrossOrigin(origins = "*")
public class CommonController {

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    @Value("${file.upload.path}")
    public  String uploadPath;
    @Value("${file.upload.address}")
    public  String uri;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成加减法验证码
     * @return
     */
    @GetMapping("/captcha")
    public AjaxResult getCode(){
        String uuid = UUID.randomUUID().toString();
        String ImageKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String capStr = null,code = null;
        BufferedImage image = null;
        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);
        //保存到redis
        redisTemplate.opsForValue().set(ImageKey,code,2, TimeUnit.MINUTES);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();

        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("验证码服务出错");
        }

        AjaxResult success = AjaxResult.success();
        success.put("uuid",uuid);
        success.put("img", Base64.encode(os.toByteArray()));

        return success;
    }

    /**
     * 上传文件,头像、Excel、简历等
     * @param file
     * @return
     */
    @PostMapping("/file/upload")
    @PreAuthorize("@ps.hasPerm('common:file:upload')")
    public AjaxResult uploadFile(@RequestBody MultipartFile file){
        AjaxResult result = new AjaxResult();
        if(file==null) return null;
        String originalFilename = file.getOriginalFilename();

        String path;
        try {
           path = FileUtils.upload(file,uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("code",500);
            result.put("msg","文件上传失败，请联系管理员");
            return result;
        }
        result.put("code",200);
        result.put("msg","文件上传成功");
        result.put("data",uri + path);
        result.put("originFileName",originalFilename);

        return result;
    }

    /**
     * 文件下载，例如报告、简历等
     * @param fileName
     * @param response
     */
    @GetMapping("/file/download")
    @PreAuthorize("@ps.hasPerm('common:file:download')")
    public void downLoadFile(@RequestParam String fileName,@RequestParam String originName, HttpServletResponse response){
        String fileType = FileUtils.getFileType(fileName);
        boolean containsAny = ArrayUtil.containsAny(FileUtils.DEFAULT_ALLOWED_EXTENSION, fileType);
        if(containsAny){
            try {
                FileUtils.downLoad(fileName,uploadPath,originName,response);
            } catch (IOException e) {
                e.printStackTrace();
                ServletUtils.renderString(response,"文件不存在");

            }
        }else {
            ServletUtils.renderString(response,"不支持该类型文件");
        }

 }


}
